<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-08-28 12:52
 *
 * 项目：rm  -  $  - tradesHelper.php
 *
 * 作者：liwei 
 */

namespace modules\levpays\table;

use Lev;
use lev\base\Modelv;
use lev\helpers\ModulesHelper;
use modules\levpays\helpers\levpaysSetHelper;
use modules\levpays\levpaysHelper;
use modules\levpays\widgets\pay\payWidget;

!defined('INLEV') && exit('Access Denied LEV');

class LevpaysTrades extends Modelv
{

    public static function tableName($tableName = '{{%levpays_trades}}', $prefix = true)
    {
        return parent::tableName($tableName ?: '{{%levpays_trades}}', $prefix); // TODO: Change the autogenerated stub
    }

    public static function paytypeid() {
        return payWidget::paytypeid();
    }
    public static function paytypeidIcon() {
        return payWidget::paytypeidIcon();
    }

    public static function tradestatus() {
        return [
            0 => '未支付',
            1 => '已支付',
            2 => '已关闭',
            3 => '已超时',
            4 => '已放弃',
            5 => '重复单',
        ];
    }

    public static function currency() {
        return [
            'CNY' => ['id'=>'CNY', 'unit'=>'元', 'mark'=>'&yen;'],
        ];
    }

    public static function tradeNoToId($tradeNo) {
        return is_numeric($tradeNo) ? $tradeNo : floatval(end(explode('T', $tradeNo)));
    }

    public static function getTradeno($id) {
        return levpaysSetHelper::tradenoPre() . Lev::addx0($id, 19);
    }

    public static function createTradeId($iden, $goodsId, $uid, $paymoney, $goodsName) {
        $tradeInfo = static::findOne(['uid'=>$uid, 'goodsid'=>$goodsId, 'iden'=>$iden, 'paymoney'=>$paymoney, 'ip'=>Lev::$app['ip'], 'tradestatus'=>0]);
        if (!$tradeInfo) {
            $tradeId = static::insert($tradeInfo = [
                'uid'         => $uid,
                'goodsid'     => $goodsId,
                'name'        => $goodsName,
                'iden'        => $iden,
                'paymoney'    => $paymoney,
                'tradestatus' => 0,
                'ip'          => Lev::$app['ip'],
                'addtime'     => Lev::$app['timestamp'],
            ], true);
            $tradeInfo['id'] = $tradeId;
        }else {
            $tradeId = $tradeInfo['id'];
        }
        static::tradeInfo($tradeId, $tradeInfo);
        return $tradeId;
    }

    public static function tradeInfo($id, $tradeInfo = []) {
        static $trades;
        !isset($trades[$id]) && $trades[$id] = $tradeInfo ?: (static::findOne(['id'=>$id]) ?: []);
        return $trades[$id];
    }

    public static function setTradePaysource($tradeNo, $paysource) {
        $tradeInfo = static::tradeInfo(static::tradeNoToId($tradeNo));
        $tradeInfo && $tradeInfo['paysource'] != $paysource &&
        static::update(['paysource'=>$paysource], ['id'=>$tradeInfo['id']]);
    }
}

class tradesHelper extends LevpaysTrades
{

}